import axios from 'axios'

const service = axios.create({
    responseType: 'arraybuffer'
})

service.interceptors.request.use(config => {
    /* 设置请求头 */
    config.headers.Authorization = window.sessionStorage.getItem('tokenStr')
    return config
}, error => {
    console.log(error)
})

service.interceptors.response.use(res => {
    /* 获请求头 */
    const headers = res.headers
    var reg = RegExp(/application\/json/)
    /* 判断请求是不是流形式传输 */
    if (headers['content-type'].match(reg)) {
        res.data = unitToString(res.data)
    } else {
        /* 引路插件 */
        let fileDownload = require('js-file-download')
        /* 获取文件名 */
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1]
        /* 获取响应类型 */
        let contentType = headers['content-type']
        /* 转换文件名，防止中文乱码 */
        fileName = decodeURIComponent(fileName)
        /* 下载文件 */
        fileDownload(res.data, fileName, contentType)
    }
}, error => {
    console.log(error)
})

/* 处理json格式转换 */
function unitToString(unitArray) {
    let encodedString = String.fromCharCode.apply(null, new Uint8Array(unitArray))
    let decodedString = decodeURIComponent(escape(encodedString))
    return JSON.parse(decodedString)
}

var base = ''

export const downloadRequest = (url, params) => {
    return service({
        method: 'get',
        url: `${base}${url}`,
        data: params
    })
}

export default service